package com.tuling.web.controller;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 甘叶勇 on 2016/7/13.
 */
@Controller
@RequestMapping("/index")
public class IndexController {
    static final String KEY = "4c456fb30fb8a6bfb58f6c8a8d526a4b";

    @RequestMapping(value = "/tuling", method = RequestMethod.GET)
    public String index() {

        return "index";
    }

    @RequestMapping(value = "/communication", method = RequestMethod.POST)
    @ResponseBody
    public String communication(@RequestParam HashMap<String, String> param) throws IOException {
        String postUrl = "http://www.tuling123.com/openapi/api";
        String data;
        ObjectMapper objectMapper = new ObjectMapper();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(outputStream);

        param.put("key", KEY);
        param.put("userid", "12345678");
        param.put("info2", "中文");


        jsonGenerator.writeObject(param);

        data = new String(outputStream.toByteArray(),"UTF-8");

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(postUrl);
        StringEntity postingString = new StringEntity(data, "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json;charset=UTF-8");
        HttpResponse response = httpClient.execute(post);

        HttpEntity httpEntity = response.getEntity();
        String result = IOUtils.toString(httpEntity.getContent(),"UTF-8");
        System.out.println(result);



        return result;
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(outputStream);

        Map<String, String> map = new HashMap<String, String>();
        map.put("account", "admin");
        map.put("info", "中文");
        jsonGenerator.writeObject(map);

        System.out.println(new String(outputStream.toByteArray()));
    }
}
